
package com.assistant.core.modules.sys.app.user;

import com.assistant.core.modules.sys.adapter.web.user.model.LoginCmd;
import com.assistant.core.modules.sys.app.user.cmd.UserInsertCmd;
import com.assistant.core.modules.sys.app.user.cmd.UserUpdateCmd;
import com.assistant.core.modules.sys.domain.user.User;
import com.assistant.core.modules.sys.domain.user.gateway.UserGateway;
import com.assistant.exception.AssistantException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserGateway gateway;

    public User login(LoginCmd loginCmd) {
        final Optional<User> userOptional = gateway.findByUsername(loginCmd.getUsername());
        if (!userOptional.isPresent()) {
            throw new AssistantException("用户名不存在或密码错误！");
        }
        if (!userOptional.get().getPassword().equals(loginCmd.getPassword())) {
            throw new AssistantException("用户名不存在或密码错误！");
        }
        return userOptional.get();
    }

    public User get(Long id) {
        return gateway.getById(id);
    }

    public List<User> list() {
        return gateway.findAll();
    }

    public void insert(UserInsertCmd cmd) {
        User user = new User();
        BeanUtils.copyProperties(cmd, user);
        gateway.save(user);
    }

    public void update(UserUpdateCmd cmd) {
        User user = gateway.getById(cmd.getId());
        BeanUtils.copyProperties(cmd, user);
        gateway.save(user);
    }

    public void delete(Long id) {
        gateway.deleteById(id);
    }
}

